<?php
/**
 * 商品属性
 * Author: hades
 * DateTime: 2020/5/16 15:47
 */

namespace App\Controller\admin;

use App\Model\GCategory;
use App\Model\GProperty;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class CategoryController
 * @package App\Controller\admin
 * @Controller(prefix="a/property")
 * @Middleware(\App\Middleware\AdminMiddleware::class)
 */
class PropertyController extends AdminBase {

    /**
     * 查询属性
     * @RequestMapping(path="lists",methods="get")
     * @return array
     */
    public function getLists() {
        $cid = (int) $this->get('cid');
        $lists = GProperty::query()
            ->where('cid', $cid)
            ->orderBy('sequence', 'desc')
            ->orderBy('id')
            ->select('id','name')
            ->get();
        return success(['lists' => $lists]);
    }

    /**
     * 添加、编辑
     * @RequestMapping(path="save",methods="post")
     * @return array
     */
    public function save() {
        $name = $this->body('name');
        $cid = $this->body('cid');
        $id = $this->body('id');
        if (empty($name) || empty($cid)) {
            return error('参数错误');
        }
        $name = mb_substr($name, 0, 20);
        // 查询父级
        $has = GCategory::query()->where('id', $cid)->count();
        if ($has == 0) {
            return error('分类不存在');
        }
        $data = ['name' => $name, 'cid' => $cid,];
        if ($id) {
            $r = GProperty::query()->where('id', $id)->update($data);
        } else {
            $r = GProperty::query()->insert($data);
        }
        return $r ? success() : error();
    }

    /**
     * 更新排序
     * @return array
     * @RequestMapping(path="sequence",methods="post")
     */
    public function postSequence() {
        $sort = $this->body('sort');
        $id = $this->body('id');
        $r = GProperty::query()
            ->where('id', $id)
            ->update(['sequence' => $sort]);
        return $r ? success() : error();
    }
}
